package com.ruoyi.system.controller;

import java.math.BigDecimal;
import java.util.List;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.domain.SysItem;
import com.ruoyi.system.domain.SysSaleRecords;
import com.ruoyi.system.service.ISysItemService;
import com.ruoyi.system.service.ISysSaleRecordsService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.system.domain.SysOrder;
import com.ruoyi.system.service.ISysOrderService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 订单Controller
 *
 * @author silencezheng
 * @date 2023-01-08
 */
@RestController
@RequestMapping("/order")
public class SysOrderController extends BaseController {
    @Autowired
    private ISysOrderService sysOrderService;
    @Autowired
    private ISysItemService sysItemService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysSaleRecordsService sysSaleRecordsService;

    /**
     * 查询订单列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SysOrder sysOrder) {
        startPage();
        List<SysOrder> list = sysOrderService.selectSysOrderList(sysOrder);
        return getDataTable(list);
    }

    /**
     * 导出订单列表
     */
    @RequiresPermissions("common:order:export")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysOrder sysOrder) {
        List<SysOrder> list = sysOrderService.selectSysOrderList(sysOrder);
        ExcelUtil<SysOrder> util = new ExcelUtil<SysOrder>(SysOrder.class);
        util.exportExcel(response, list, "订单数据");
    }

    /**
     * 获取订单详细信息
     */
    @GetMapping("/getItemsByOrder")
    public TableDataInfo getItemsByOrder(Long orderId) {
        startPage();
        List<SysItem> list = sysItemService.getItemsByOrder(orderId);
        return getDataTable(list);
    }

    /**
     * 生成订单
     */
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysOrder sysOrder) {
        return toAjax(sysOrderService.insertSysOrder(sysOrder));
    }

    /**
     * 修改订单
     */
    @RequiresPermissions("system:order:edit")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysOrder sysOrder) {
        return toAjax(sysOrderService.updateSysOrder(sysOrder));
    }

    /**
     * 删除订单
     */
    @RequiresPermissions("system:order:remove")
    @Log(title = "订单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(sysOrderService.deleteSysOrderByIds(ids));
    }

    /**
     * 支付订单
     */
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping("payOrder")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult payOrder(@RequestBody SysOrder sysOrder) {
        //减少账户余额
        SysUser user = new SysUser();
        user.setUserId(sysOrder.getCustomerId());
        SysUser sysUser = userService.selectUserById(user.getUserId());
        user.setRemark(String.valueOf(new BigDecimal(sysUser.getRemark()).subtract(sysOrder.getAmount())));
        userService.updateUserProfile(user);
        //生成商品销售记录
        List<SysItem> list = sysItemService.getItemsByOrder(sysOrder.getId());
        list.forEach(i -> {
            SysSaleRecords sysSaleRecords = new SysSaleRecords();
            sysSaleRecords.setItemName(i.getName());
            sysSaleRecords.setCustomer(SecurityUtils.getUsername());
            sysSaleRecords.setOrderId(sysOrder.getId());
            sysSaleRecords.setPicture(i.getPicture());
            sysSaleRecords.setPrice(i.getPrice());
            sysSaleRecordsService.insertSysSaleRecords(sysSaleRecords);
            //更改商品库存及销售数量
        });

        //更改订单状态
        SysOrder order = new SysOrder();
        order.setId(sysOrder.getId());
        order.setStatus(sysOrder.getStatus());
        return toAjax(sysOrderService.updateSysOrder(order));
    }
}
